package com.crane.app.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.crane.common.core.dto.MultiResponse;
import com.crane.common.core.dto.Response;
import com.crane.common.core.dto.SingleResponse;
import com.crane.common.core.utils.BaseContextHandler;
import com.crane.common.core.utils.StringUtil;
import com.crane.common.framework.utils.BeanUtil;
import com.crane.oss.app.bean.req.AppCommentHomeWorkReq;
import com.crane.oss.app.bean.req.AppEditHomeWorkReq;
import com.crane.oss.app.bean.req.AppPublishHomeWorkReq;
import com.crane.oss.app.bean.req.AppQueryHomeWorkDetailReq;
import com.crane.oss.app.bean.req.AppQueryHomeWorkReq;
import com.crane.oss.app.bean.req.AppSubmitHomeWorkReq;
import com.crane.oss.app.bean.resp.AppHomeWorkCommentDetailResp;
import com.crane.oss.app.bean.resp.AppHomeWorkCommentDetailResp.FinishInfo;
import com.crane.oss.app.bean.resp.AppHomeWorkDetailResp;
import com.crane.oss.app.bean.resp.AppHomeWorkListResp;
import com.crane.oss.app.service.AppUserService;
import com.crane.oss.enums.GradeEnum;
import com.crane.oss.enums.HomeWorkStatusEnum;
import com.crane.oss.enums.SectionEnum;
import com.crane.oss.school.bean.resp.StudentResp;
import com.crane.oss.school.bean.resp.TeacherResp;
import com.crane.oss.school.service.StudentService;
import com.crane.oss.school.service.TeacherService;
import com.crane.oss.sports.XunFeiHomeWorkApiService;
import com.crane.oss.xunfei.req.CheckHomeWorkReq;
import com.crane.oss.xunfei.req.CommentHomeWorkReq;
import com.crane.oss.xunfei.req.DeleteHomeWorkReq;
import com.crane.oss.xunfei.req.HomeWorkDetailReq;
import com.crane.oss.xunfei.req.PublishHomeWorkReq;
import com.crane.oss.xunfei.req.QueryHomeWorkListReq;
import com.crane.oss.xunfei.req.SubmitHomeWorkReq;
import com.crane.oss.xunfei.resp.ApiListResponse;
import com.crane.oss.xunfei.resp.ApiSingleResponse;
import com.crane.oss.xunfei.resp.HomeWorkDetailResp;
import com.crane.oss.xunfei.resp.HomeWorkListResp;

import cn.hutool.core.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

@Api(value = "HomeWorkController", tags = { "体育作业" })
@RestController
@RequestMapping("/app/homework")
public class HomeWorkController {
	
    @Resource
    AppUserService appUserService;

    @Resource
    TeacherService teacherService;

	@Resource
	XunFeiHomeWorkApiService xunFeiHomeWorkApiService;
	
	@Resource
	StudentService studentService;
	
	@ApiOperation(value = "老师-删除作业", notes = "老师-删除作业:只能删除未开始的作业")
	@ApiImplicitParam(name = "homeworkId", value = "作业ID", paramType = "path", dataType = "String")
	@GetMapping("/delete/{homeworkId}")
	public Response delete(@PathVariable("homeworkId") String homeworkId) {
        Long userId= BaseContextHandler.getUserId();
        String partyId = null;
        TeacherResp teacherResp=teacherService.queryTeacherByAppUserId(userId);
        if (null != teacherResp)
        	partyId = teacherResp.getPartyId().toString();
        
		DeleteHomeWorkReq delReq = new DeleteHomeWorkReq();
		delReq.setHomeworkCornId(homeworkId);
		
		ApiSingleResponse response = xunFeiHomeWorkApiService.deleteHomeWork(delReq, partyId, null, userId.toString());
		if (null != response && response.getMsg().equals("success")) {
			return Response.buildSuccess();
		}
		return Response.buildFailure("请求接口失败");
	}

	@ApiOperation(value = "老师/家长-作业列表", notes = "老师/家长-作业列表")
	@ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "AppQueryHomeWorkReq")
	@PostMapping("/list")
	public MultiResponse<AppHomeWorkListResp> list(@RequestBody @Valid AppQueryHomeWorkReq request) {
		Long userId=BaseContextHandler.getUserId();
		String partyId = null;
		QueryHomeWorkListReq listReq = new QueryHomeWorkListReq();
		listReq.setType(request.getType());
		listReq.setPage(request.getPageNo());
		listReq.setLimit(request.getPageSize());

		if (null != request.getBeginTime())
			listReq.setBeginTime(request.getBeginTime().getTime());

		if (null != request.getEndTime())
			listReq.setEndTime(request.getEndTime().getTime());
		
		if (StringUtil.isNotBlank(request.getStudentId())) {
			listReq.setStudentId(request.getStudentId());
			//表示为家长
			StudentResp studentResp=appUserService.getDefaultStudent(userId);
			if(null != studentResp)
				partyId = studentResp.getPartyId().toString();
		} else {
			//表示老师
			TeacherResp teacherResp=teacherService.queryTeacherByAppUserId(userId);
			partyId = teacherResp.getPartyId().toString();
		}

		ApiListResponse<HomeWorkListResp> response = xunFeiHomeWorkApiService.getHomeWorkList(listReq, partyId, null, userId.toString());
		if (null != response && response.getMsg().equals("success")) {
			List<AppHomeWorkListResp> returnList = new ArrayList<AppHomeWorkListResp>();
			for (HomeWorkListResp temp : BeanUtil.copyList(response.getData(), HomeWorkListResp.class)) {
				AppHomeWorkListResp resp = new AppHomeWorkListResp();
				BeanUtil.copyProperties(temp, resp);
				if (null != temp.getBeginTime())
				resp.setBeginTime(DateUtil.date(temp.getBeginTime()));

				if (null != temp.getCreateTime())
				resp.setCreateTime(DateUtil.date(temp.getCreateTime()));

				if (null != temp.getSubmitDate())
				resp.setSubmitDate(DateUtil.date(temp.getSubmitDate()));
				
				if (null != temp.getSubmitTime()) {
					Integer limitTime = (int) (temp.getSubmitTime()/(24*60*60*1000));
					resp.setSubmitTime(limitTime);
				}
				
				List<String> pictureUrls = new ArrayList<String>();
				if (StringUtil.isNotBlank(temp.getPictureUrl())) {
					if (temp.getPictureUrl().indexOf(",") == 1) {
						String[] transition = temp.getPictureUrl().split(",");
						for (int i = 0; i < transition.length; i++) {
							pictureUrls.add(transition[i]);
						}
					} else {
						pictureUrls.add(temp.getPictureUrl());
					}
					resp.setPictureUrl(pictureUrls);
				}

				List<String> videoUrls = new ArrayList<String>();
				if (StringUtil.isNotBlank(temp.getVideoUrl())) {
					if (temp.getVideoUrl().indexOf(",") == 1) {
						String[] transition = temp.getVideoUrl().split(",");
						for (int i = 0; i < transition.length; i++) {
							videoUrls.add(transition[i]);
						}
					} else {
						videoUrls.add(temp.getVideoUrl());
					}
					resp.setVideoUrl(videoUrls);
				}

				resp.setStatusCn(HomeWorkStatusEnum.getRemark(temp.getStatus()));

				returnList.add(resp);
			}
			return MultiResponse.of(returnList, response.getTotal(), request);
		}
		return MultiResponse.buildFailure("请求接口失败");
	}

	@ApiOperation(value = "家长-提交作业", notes = "家长-提交作业")
	@ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "AppSubmitHomeWorkReq")
	@PostMapping("/submit")
	public Response submit(@RequestBody @Valid AppSubmitHomeWorkReq request) {
		Long userId= BaseContextHandler.getUserId();
		String partyId = null;
        StudentResp studentResp=appUserService.getDefaultStudent(userId);
        if (studentResp != null)
        	partyId = studentResp.getPartyId().toString();
		SubmitHomeWorkReq submitReq = new SubmitHomeWorkReq();

		BeanUtil.copyProperties(request, submitReq);
		submitReq.setStudentId(request.getStudentId().toString());

		ApiSingleResponse response = xunFeiHomeWorkApiService.submitHomeWork(submitReq, partyId, null, userId.toString());
		if (null != response) {
			if (response.getMsg().equals("success")) {
				return Response.buildSuccess();
			} else {
				return Response.buildFailure(response.getMsg());
			}
		}
		return Response.buildFailure("请求接口失败");
	}
	
	@ApiOperation(value = "老师-批改作业", notes = "老师-批改作业")
	@ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "AppCommentHomeWorkReq")
	@PostMapping("/comment")
	public Response comment(@RequestBody @Valid AppCommentHomeWorkReq request) {
		Long userId= BaseContextHandler.getUserId();
		String partyId = null;
		TeacherResp teacherResp=teacherService.queryTeacherByAppUserId(userId);
		if (null != teacherResp) {
			partyId = teacherResp.getPartyId().toString();
			CommentHomeWorkReq commentReq = new CommentHomeWorkReq();
			BeanUtil.copyProperties(request, commentReq);
			commentReq.setId(request.getHomeworkId());
			
			ApiSingleResponse response = xunFeiHomeWorkApiService.commentHomeWork(commentReq, partyId, null, userId.toString());
			if (null != response && response.getMsg().equals("success")) {
				return Response.buildSuccess();
			} else {
				return Response.buildFailure(response.getMsg());
			}
		}
		return Response.buildFailure("请求接口失败");
	}

	@ApiOperation(value = "老师-发布作业", notes = "老师-发布作业")
	@ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "AppPublishHomeWorkReq")
	@PostMapping("/publish")
	public Response publish(@RequestBody @Valid AppPublishHomeWorkReq request) {
        Long userId= BaseContextHandler.getUserId();
        String partyId = null;
        TeacherResp teacherResp=teacherService.queryTeacherByAppUserId(userId);
        if (null != teacherResp) {
            partyId = teacherResp.getPartyId().toString();
            
    		PublishHomeWorkReq publishReq = new PublishHomeWorkReq();

    		BeanUtil.copyProperties(request, publishReq);
    		publishReq.setRemark(request.getReamrk());
    		publishReq.setSubmitTime(request.getSubmitTime()*(24*60*60*1000));
    		publishReq.setCampusId(request.getSchoolId().toString());
    		publishReq.setSectionId(SectionEnum.getAlias(Integer.valueOf(request.getSectionId())));
    		publishReq.setNj(GradeEnum.getAlias(request.getNj()));
    		publishReq.setClassId(request.getClassId().toString());
    		publishReq.setBeginTime(request.getBeginTime().getTime());
    		publishReq.setEndTime(request.getEndTime().getTime());
    		publishReq.setTeacherId(teacherResp.getTeacherId().toString());

    		ApiSingleResponse response = xunFeiHomeWorkApiService.publishHomeWork(publishReq, partyId, null, userId.toString());
    		if (null != response && response.getMsg().equals("success")) {
    			return Response.buildSuccess();
    		}
        }
		return Response.buildFailure("请求接口失败");
	}
	
	@ApiOperation(value = "老师-编辑作业", notes = "老师-编辑作业：只能编辑已发布且无人提交的作业")
	@ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "AppEditHomeWorkReq")
	@PostMapping("/edit")
	public Response edit(@RequestBody @Valid AppEditHomeWorkReq request) {
        Long userId= BaseContextHandler.getUserId();
        String partyId = null;
        TeacherResp teacherResp=teacherService.queryTeacherByAppUserId(userId);
        if (null != teacherResp) {
            partyId = teacherResp.getPartyId().toString();
            
            CheckHomeWorkReq checkReq = new CheckHomeWorkReq();
            checkReq.setId(request.getId());
            ApiSingleResponse checkResponse = xunFeiHomeWorkApiService.checkHomeWork(checkReq, partyId, null, userId.toString());
            if (null != checkResponse && checkResponse.getCode() == 200) {
        		PublishHomeWorkReq publishReq = new PublishHomeWorkReq();
        		BeanUtil.copyProperties(request, publishReq);
        		publishReq.setSubmitTime(request.getSubmitTime()*(24*60*60*1000));
        		publishReq.setCampusId(request.getSchoolId().toString());
        		publishReq.setSectionId(SectionEnum.getAlias(Integer.valueOf(request.getSectionId())));
        		publishReq.setNj(GradeEnum.getAlias(request.getNj()));
        		publishReq.setClassId(request.getClassId().toString());
        		publishReq.setBeginTime(request.getBeginTime().getTime());
        		publishReq.setEndTime(request.getEndTime().getTime());
        		publishReq.setTeacherId(teacherResp.getTeacherId().toString());

        		ApiSingleResponse response = xunFeiHomeWorkApiService.publishHomeWork(publishReq, partyId, null, userId.toString());
        		if (null != response && response.getMsg().equals("success")) {
        			return Response.buildSuccess();
        		}
            } else {
            	return Response.buildFailure("当前作业已有人提交不可修改");
            }
            
        }
		return Response.buildFailure("请求接口失败");
	}
	
	@ApiOperation(value = "老师-作业详情", notes = "老师-作业详情")
	@ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "AppQueryHomeWorkDetailReq")
	@PostMapping("/commentDetail")
	public SingleResponse<AppHomeWorkCommentDetailResp> commentDetail(@RequestBody @Valid AppQueryHomeWorkDetailReq request) {
		Long userId=BaseContextHandler.getUserId();
		TeacherResp teacherResp=teacherService.queryTeacherByAppUserId(userId);
		String partyId = teacherResp.getPartyId().toString();
		
		HomeWorkDetailReq detailReq = new HomeWorkDetailReq();
		detailReq.setClassId(request.getClassId());
		detailReq.setHomeworkId(request.getHomeworkId());
		
		ApiListResponse<HomeWorkDetailResp> response = xunFeiHomeWorkApiService.getHomeWorkDetail(detailReq, partyId.toString(), null, userId.toString());
		if (null != response && response.getMsg().equals("success")) {
			AppHomeWorkCommentDetailResp resp = new AppHomeWorkCommentDetailResp();
			List<FinishInfo> completedList = new ArrayList<FinishInfo>();
			List<FinishInfo> undoneList = new ArrayList<FinishInfo>();
			
			for (HomeWorkDetailResp detail : BeanUtil.copyList(response.getData(), HomeWorkDetailResp.class)) {
				BeanUtil.copyProperties(detail, resp);
				
				AppHomeWorkCommentDetailResp.FinishInfo info = new AppHomeWorkCommentDetailResp().new FinishInfo();
				BeanUtil.copyProperties(detail, info);
				
				info.setHeadUrl(null);
				if (StringUtil.isNotBlank(detail.getStudentId())) {
					StudentResp student = studentService.queryStudentOnInit(Long.valueOf(detail.getStudentId()));
					if (null != student) {
						info.setHeadUrl(student.getImg());
					}
				}
				
				List<String> pictureUrls = new ArrayList<String>();
				if (StringUtil.isNotBlank(detail.getPictureUrl())) {
					if (detail.getPictureUrl().indexOf(",") == 1) {
						String[] temp = detail.getPictureUrl().split(",");
						for (int i = 0; i < temp.length; i++) {
							pictureUrls.add(temp[i]);
						}
					} else {
						pictureUrls.add(detail.getPictureUrl());
					}
					info.setPictureUrls(pictureUrls);
				}

				List<String> videoUrls = new ArrayList<String>();
				if (StringUtil.isNotBlank(detail.getVideoUrl())) {
					if (detail.getVideoUrl().indexOf(",") == 1) {
						String[] temp = detail.getVideoUrl().split(",");
						for (int i = 0; i < temp.length; i++) {
							videoUrls.add(temp[i]);
						}
					} else {
						videoUrls.add(detail.getVideoUrl());
					}
					info.setVideoUrls(videoUrls);
				}
				
				//老师评语不为空，表示已批改
				info.setIsMark("0");
				if (StringUtil.isNotBlank(detail.getTeacherComment())) {
					info.setIsMark("1");
				}
				
				//未完成
				if (0 == detail.getFlag()) {
					undoneList.add(info);
				}
				
				//已完成
				if (1 == detail.getFlag()) {
					completedList.add(info);
				}
			}
			resp.setCompletedList(completedList);
			resp.setUndoneList(undoneList);
			
			return SingleResponse.of(resp);
		}
		
		return SingleResponse.buildFailure("请求失败");
	}

	@ApiOperation(value = "家长-作业详情", notes = "家长-作业详情")
	@ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "AppQueryHomeWorkDetailReq")
	@PostMapping("/detail")
	public MultiResponse<AppHomeWorkDetailResp> detail(@RequestBody @Valid AppQueryHomeWorkDetailReq request) {
		Long userId=BaseContextHandler.getUserId();
		String partyId = null;
		if (StringUtil.isNotBlank(request.getStudentId())) {
			//表示为家长
			StudentResp studentResp=appUserService.getDefaultStudent(userId);
			if(null != studentResp)
				partyId = studentResp.getPartyId().toString();
		} else {
			return MultiResponse.buildFailure("请选择您要查询的学生");
		}
		
		HomeWorkDetailReq detailReq = new HomeWorkDetailReq();
		detailReq.setClassId(request.getClassId());
		detailReq.setHomeworkId(request.getHomeworkId());
		detailReq.setStudentId(request.getStudentId());

		ApiListResponse<HomeWorkDetailResp> response = xunFeiHomeWorkApiService.getHomeWorkDetail(detailReq, partyId.toString(), null, userId.toString());
		if (null != response && response.getMsg().equals("success")) {
			List<AppHomeWorkDetailResp> returnList = new ArrayList<AppHomeWorkDetailResp>();
			for (HomeWorkDetailResp detail : BeanUtil.copyList(response.getData(), HomeWorkDetailResp.class)) {
				AppHomeWorkDetailResp appResp = new AppHomeWorkDetailResp();
				BeanUtil.copyProperties(detail, appResp);

				List<String> pictureUrls = new ArrayList<String>();
				if (StringUtil.isNotBlank(detail.getPictureUrl())) {
					if (detail.getPictureUrl().indexOf(",") == 1) {
						String[] temp = detail.getPictureUrl().split(",");
						for (int i = 0; i < temp.length; i++) {
							pictureUrls.add(temp[i]);
						}
					} else {
						pictureUrls.add(detail.getPictureUrl());
					}
					appResp.setPictureUrls(pictureUrls);
				}

				List<String> videoUrls = new ArrayList<String>();
				if (StringUtil.isNotBlank(detail.getVideoUrl())) {
					if (detail.getVideoUrl().indexOf(",") == 1) {
						String[] temp = detail.getVideoUrl().split(",");
						for (int i = 0; i < temp.length; i++) {
							videoUrls.add(temp[i]);
						}
					} else {
						videoUrls.add(detail.getVideoUrl());
					}
					appResp.setVideoUrls(videoUrls);
				}
				
				returnList.add(appResp);
			}

			return MultiResponse.of(returnList,returnList.size());
		}
		return MultiResponse.buildFailure("请求接口失败");
	}

}
